package com.zd.wechatPlatform.controller;

import java.util.Arrays;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.zd.wechatPlatform.cache.map.CodeValueCache;
import com.zd.wechatPlatform.common.utils.EncryptUtil;
import com.zd.wechatPlatform.common.utils.LogUtils;
import com.zd.wechatPlatform.common.utils.XMLUtil;
import com.zd.wechatPlatform.service.IWeixinMsgHandler;

/**
 * 微信公众号基本服务
 * @author wangliming
 *
 * @date 2018年10月31日下午3:37:57
 */
@Controller
public class WeixinController extends BaseController {
	
	@Autowired
	private CodeValueCache codeValueCache;
	
	
	@Autowired
	@Qualifier("weixinMsgHandler")
	private IWeixinMsgHandler weixinMsgHandler;
	
	
	/**
	 * 微信公众号接入校验
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = { "weixin", "" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
	public String accessWeixin(HttpServletRequest request, HttpServletResponse response){
		try {
			String echostr = request.getParameter("echostr");
			LogUtils.info("echostr:" + echostr);
			if (validaReq(request)) {
				return echostr;
			}
		} catch (Exception e) {
			return "error";
		}
		return "error";
	}
	
	
	@ResponseBody
	@RequestMapping(value = { "weixin" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	public String weixinService(final HttpServletRequest request, final HttpServletResponse response) throws Exception{
		//获取微信推送的事件消息
		final Map<String, String> msgMap = XMLUtil.parseXmlFromInputStream(request.getInputStream());
		LogUtils.info("requestMap:" + JSONObject.toJSONString(msgMap));
		
		new Thread(new Runnable() {
			public void run() {
				try {
					try {
						weixinMsgHandler.handlerMsg(msgMap);
					} catch (Exception e) {
						LogUtils.error("weixinService exception:" + e.getMessage(), e);
					}
				} catch (Exception e) {
					LogUtils.error("Exception ", e);
				}
			}
		}).start();
		return "success";
	}
	
	
	private boolean validaReq(HttpServletRequest request) {
		try {
			String signature = request.getParameter("signature");
			String timestamp = request.getParameter("timestamp");
			String nonce = request.getParameter("nonce");
			String token = codeValueCache.getSysValue("WX_VALIDATE_TOKEN").get(0).getValue();
			String[] strings = new String[3];
			strings[0] = timestamp;
			strings[1] = nonce;
			strings[2] = token;
			Arrays.sort(strings);
			StringBuffer sb = new StringBuffer();
			for (String str : strings) {
				sb.append(str);
			}
			String string = EncryptUtil.Encrypt(sb.toString(), "SHA-1");
			return string.equals(signature);
		} catch (Exception e) {
		}
		return false;
	}
}
